//
//  STCommoditySegmentView.swift
//  iPhone
//
//  Created by Toj on 8/9/22.
//

import UIKit
import SwiftUI

protocol STCommoditySegmentViewDelegate: NSObjectProtocol {
    
    func commoditySegmentView(_ view: STCommoditySegmentView, didTapSegment index: Int, title: String)
}

class STCommoditySegmentView: UIView {

    var titles: [String] = [] {
        didSet {
            contentViews = []
            setupContent()
        }
    }
    
    weak var delegate: STCommoditySegmentViewDelegate?
    
    var selectedIndex = 0 {
        willSet {
            if selectedIndex == newValue { return }
            if contentViews.isEmpty || newValue >= contentViews.count { return }
            selectedView = contentViews[newValue]
            tapSegmentItemHandle(index: newValue)
        }
    }
    
    var isSelectedImageViewHidden = false {
        didSet {
            selectedImageView.isHidden = isSelectedImageViewHidden
        }
    }
    
    var normalFont: UIFont = UIFont.boldSystemFont(ofSize: 14) {
        didSet {
            contentViews.forEach { view in
                view.titleLabel?.font = normalFont
            }
        }
    }
    var selectedFont: UIFont = UIFont.boldSystemFont(ofSize: 18) {
        didSet {
            selectedView?.titleLabel?.font = selectedFont
        }
    }
    var selectedView: UIButton? {
        willSet {
            selectedView?.isSelected = false
            selectedView?.titleLabel?.font = normalFont
            newValue?.isSelected = true
            newValue?.titleLabel?.font = selectedFont
        }
    }
    
    var segmentBackgroundColor = UIColor(hex: 0x28333B) {
        didSet {
            guard segmentGradationColors.isEmpty else { return }
            segmentView.backgroundColor = segmentBackgroundColor
        }
    }
    
    var segmentGradationColors: [CGColor] = [] {
        didSet {
            guard !segmentGradationColors.isEmpty else { return }
            segmentView.backgroundColor = nil
        }
    }
    
    private var contentViews: [UIButton] = []
    
    private lazy var segmentView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0x28333B)
        return view
    }()
    
    private lazy var selectedImageView: UIImageView = {
       let view = UIImageView()
        view.image = "commodity_segment".to_image
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        clipsToBounds = true
        backgroundColor = UIColor(hex: "#171B22")
        addSubview(segmentView)
        addSubview(selectedImageView)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if contentViews.isEmpty { return }
        
        let selfWidth = frame.width
        let selfHeight = frame.height
        let width = selfWidth / CGFloat(titles.count)
        var x = CGFloat.zero
        let y: CGFloat = 4
        let height = selfHeight - 4
        var index = 0
        contentViews.forEach { view in
            x = CGFloat(index) * width
            view.frame = CGRect(x: x, y: y, width: width, height: height)
            index += 1
        }
        let offset: CGFloat = 18
        selectedImageView.frame = CGRect(x: 0, y: 0, width: width + offset * 2 , height: selfHeight)
        selectedImageView.center.x = width * (CGFloat(selectedIndex) + 0.5)
        segmentView.frame = CGRect(x: 0, y: y, width: selfWidth, height: height)
        
        if segmentGradationColors.isEmpty { return }
        segmentView.gd_add(colors: segmentGradationColors, direction: .topToBottom)
    }
    
    @objc private func didTapSegmentItem(sender: UIButton) {
        let index = sender.tag - 100
        if index == selectedIndex { return }
        selectedIndex = index
        let title = titles[index]
        delegate?.commoditySegmentView(self, didTapSegment: index, title: title)
    }
    
    private func tapSegmentItemHandle(index: Int) {
        guard let sender = selectedView else { return }
        UIView.animate(withDuration: 0.2) {
            self.selectedImageView.center.x = sender.frame.width * (CGFloat(index) + 0.5)
        }
    }
    
    deinit {
        // print("-->toj: STCommoditySegmentView deinit")
    }
}

extension STCommoditySegmentView {
    private func setupContent() {
        var index = 0
        titles.forEach { title in
            let view = UINormalButton()
            view.setTitleColor(UIColor(hex: "#DDDDDD"), for: .normal)
            view.setTitleColor(UIColor(hex: "#99773C"), for: .selected)
            view.titleLabel?.font = normalFont
            view.backgroundColor = .clear
            view.setTitle(title, for: .normal)
            view.tag = index + 100
            view.addTarget(self, action: #selector(didTapSegmentItem(sender:)), for: .touchUpInside)
            contentViews.append(view)
            addSubview(view)
            if index == selectedIndex {
                selectedView = view
            }
            index += 1
        }
    }
}
